package com.gdou.crrp.service;

import com.alibaba.fastjson.JSONObject;
import com.gdou.crrp.common.SmsAPI;
import com.gdou.crrp.common.VerifyAPI;
import com.gdou.crrp.entity.User;
import com.gdou.crrp.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    //判断账号是否存在
    public boolean isExist(String phone){
        User user = userRepository.findByPhone(phone);
        if (user == null){
            return false;
        }
        return true;
    }

    /**
     * 用户登录
     * @param phone
     * @param password
     * @param session
     * @return
     */
    public String login(String phone, String password, HttpSession session){
        Boolean exist = isExist(phone);
        if (exist == true){
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            User user = userRepository.findByPhone(phone);
            String truePhone = user.getPhone();
            String truePassword = user.getPassword();
            if (phone.equals(truePhone) && password.equals(truePassword)){
                session.setAttribute("phone",phone);
                session.setAttribute("id",user.getId());
                return "success";
            }else {
                return "error";
            }
        }
        return "void";
    }

    /**
     * 用户注册
     * @param phone
     * @param session
     */
    private static final String KEY = "GDOU"; //自定义秘钥

    //生成并发送短信验证码
    public void sendSms(String phone,HttpSession session){
        //产生6位验证码
        int num = (int)((Math.random()*9+1)*100000);
        String code = String.valueOf(num);
        //保存手机号码和验证码
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("phone",phone);
        paramMap.put("code",code);
        //调用接口
        SmsAPI.sendSms(paramMap);  //要用时再打开
        //保存验证码到session
        session.setAttribute("code",code);
        System.out.println("短信发送成功，验证码为：" + code);
    }

    //生成比对哈希值
    public String comparison(String phone,long oldtime,HttpSession session) {
        sendSms(phone,session); //此处执行发送短信验证码方法
        String code = (String) session.getAttribute("code");// 后台得到验证码
        String hash =  DigestUtils.md5DigestAsHex((KEY + "@" + oldtime + "@" + code).getBytes());//生成初始哈希值
        session.setAttribute("hash",hash);
        session.setAttribute("tamp",oldtime);
        return "请等待验证码接收";
    }

    //注册业务
    public String register(User user,String input_code,HttpSession session){
        String oldHash = (String) session.getAttribute("hash");
        Long tamp = (Long) session.getAttribute("tamp");
        Long currentTime = Calendar.getInstance().getTimeInMillis();//获取当前时间戳
        String newHash = DigestUtils.md5DigestAsHex((KEY + "@" + tamp + "@" + input_code).getBytes());//生成新的哈希值
        //判断账号是否存在
        Boolean exist = isExist(user.getPhone());
        if (exist == false){
            //校验时间
            if (tamp.compareTo(currentTime)> 0) {
                //校验验证码
                if (newHash.equalsIgnoreCase(oldHash)){
                    User newUser = new User();
                    newUser.setPhone(user.getPhone());
                    newUser.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
                    int id = userRepository.findMaxUserId();
                    id = id+1;
                    newUser.setName("默认用户"+id);
                    userRepository.save(newUser);
                    return "success";
                }else {
                    return "error";
                }
            } else {
                return "overtime";
            }
        }
        return "exist";
    }

    //身份证验证业务
    public boolean verify(User user) throws Exception {
        String name = user.getName();
        String identity = user.getIdentity();
        JSONObject verifyMessages = VerifyAPI.verifyIDCard(name,identity);
        if(verifyMessages.getString("status") == "01"){
            System.out.println("后台展示成功验证的身份信息：" + verifyMessages);
            return true;
        }
        return false;
    }

    //显示用户信息业务
    public User showUserInfo(String phone,HttpSession session){
        phone = (String) session.getAttribute("phone");
        User user = new User();
        user = userRepository.findByPhone(phone);
        return user;
    }

    //获取用户信息业务
    public User userInfo(String phone){
        return userRepository.findByPhone(phone);
    }

    //修改用户信息业务
    public void updateUserInfo(User user){
        userRepository.save(user);
        System.out.println("修改后用户信息："+user);
    }
}
